<!-- BMS控制 -->
<template>
  <div class="locationIndexPage">
    <div class="menu-container ">
      <div class="custom-wrapper warp">
        <!-- <div class="serach">
          <el-input style="max-width: 180px" placeholder="Please input" class="input-with-select">
            <template #append>
              <el-button icon="search" />
            </template>
</el-input>

</div>
<el-tree ref="deptTreeRef" class="mt-2" :data="deptList" :props="{ children: 'children', label: 'label', disabled: '' }"
  :expand-on-click-node="false" default-expand-all /> -->
        <el-card shadow="never" class="elTree">
          <div class="client">
            <div class="list">
              <el-icon style="margin-right: 5px" size="20">
                <UserFilled />
              </el-icon>
              客户列表
            </div>
            <!-- <el-button type="primary" size="small" @click="handleOpenDialog()">添加</el-button> -->
          </div>
          <div style="height: 150px;overflow-y: scroll;scrollbar-color: black transparent;">
            <!-- @node-contextmenu="contextmenuClick" -->
            <dept-tree ref="DeptTrees" v-model="queryParams.customerId" @node-click="handleQuery" />
          </div>

        </el-card>
      </div>
      <!--右键显示的菜单组件-->
      <div v-show="treeRightMenuShow" class="tree_rightmenu" :style="{ ...rightTreeMenuStyle }">
        <div class="tree_rightmenu_item" @click="refresh">刷新</div>
        <div class="tree_rightmenu_item" @click="handleOpenDialog()">新增客户</div>
        <div class="tree_rightmenu_item" @click="handleOpenDialog('edit')">管理客户</div>
        <div class="tree_rightmenu_item" @click="deletecustomer">删除客户</div>
        <div class="tree_rightmenu_item" @click="resetPsw">重置密码</div>
        <div class="tree_rightmenu_item" @click="updatecustomer">转移客户</div>
        <div class="tree_rightmenu_item" @click="updatedevice">转入设备</div>
      </div>
      <div class="device-wrapper warp">
        <el-menu unique-opened active-text-color="#409eff" background-color="#2b2b2b" class="el-menu-vertical-demo"
          default-active="Historical" text-color="#fff" @select="handleSelect">
          <SidebarMenuItem2 v-for="route in accountManagementRoute" :key="route.path" :item="route"
            :base-path="resolvePath(route.path)" />
        </el-menu>



        <!-- <el-menu unique-opened active-text-color="#409eff" background-color="#2b2b2b" class="el-menu-vertical-demo"
          default-active="2" text-color="#fff" @select="handleSelect">
          <el-menu-item index="Historical">
            <el-icon><icon-menu /></el-icon>
            <span>历史数据</span>
          </el-menu-item>
          <el-menu-item index="warining">
            <el-icon><icon-menu /></el-icon>
            <span>报警管理</span>
          </el-menu-item>
          <el-sub-menu index="2">
            <template #title>
              <el-icon>
                <Setting />
              </el-icon>
              <span>财务管理</span>
            </template>
            <el-menu-item index="2-1">收入记录</el-menu-item>
            <el-menu-item index="2-2">消费记录</el-menu-item>
            <el-menu-item index="2-3">续费设备记录</el-menu-item>
          </el-sub-menu>
          <el-menu-item index="account">
            <el-icon><icon-menu /></el-icon>
            <span>日志管理</span>
          </el-menu-item>
          <el-sub-menu index="4">
            <template #title>
              <el-icon>
                <Setting />
              </el-icon>
              <span>运营管理</span>
            </template>
            <el-menu-item index="4-1">运营统计</el-menu-item>
            <el-menu-item index="4-2">里程统计</el-menu-item>
          </el-sub-menu>
          <el-menu-item index="ElectronicFence">
            <el-icon><icon-menu /></el-icon>
            <span>电子围栏</span>
          </el-menu-item>
        </el-menu> -->
      </div>
    </div>
    <div class="map-container">
      <component :is="componentToShow" ref="AllchildRef" :ld="queryParams.customerId"></component>
    </div>
    <el-drawer v-model="dialog.visible" :title="dialog.title" width="80vw">
      <div class="div-container">
        <el-form ref="userFormRef" :model="formData" :rules="deviceRules" label-width="80px">
          <el-form-item label="客户名称" prop="customer.customerName">
            <el-input autocomplete="off" placeholder="请输入" v-model="formData.customer.customerName" />
          </el-form-item>
          <el-form-item label="昵称" prop="contact.name">
            <el-input v-model="formData.contact.name" placeholder="请输入昵称" />
          </el-form-item>
          <el-form-item label="用户名" prop="contact.username">
            <el-input v-model="formData.contact.username" :readonly="!!formData.contact.id" placeholder="请输入用户名" />
          </el-form-item>
          <el-form-item label="用户密码" prop="contact.password" v-if="dialog.title !== '编辑客户'">
            <el-input v-model="formData.contact.password" placeholder="请输入密码" maxlength="11" />
          </el-form-item>
          <!-- <el-form-item label="所属客户" prop="contact.customerId">
            <el-tree-select v-model="formData.contact.customerId" placeholder="请选择所属客户"
              :props="{ children: 'children', label: 'customerName', value: 'id' }" :data="deptOptions" filterable
              check-strictly :render-after-expand="false" />
          </el-form-item> -->
          <el-form-item label="角色" prop="contact.roleIdList">
            <el-select v-model="formData.contact.roleIdList" multiple placeholder="请选择">
              <el-option v-for="item in roleOptions" :key="item.value" :label="item.label"
                :value="item.value ? item.value : ''" />
            </el-select>
          </el-form-item>

          <el-form-item label="手机号码" prop="contact.phone">
            <el-input v-model="formData.contact.phone" placeholder="请输入手机号码" maxlength="11" />
          </el-form-item>

          <el-form-item label="用户状态">
            <el-radio-group v-model="formData.contact.enableFlag">
              <el-radio value="ENABLE">正常</el-radio>
              <el-radio value="DISABLE">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="客户状态">
            <el-radio-group v-model="formData.customer.enableFlag">
              <el-radio value="ENABLE">正常</el-radio>
              <el-radio value="DISABLE">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="info">
            取消
          </el-button>
          <el-button type="primary" @click="handleSubmit">
            确定
          </el-button>
        </div>
      </template>
    </el-drawer>
    <el-dialog v-model="updateshow" title="转移客户" width="500">
      <div>
        <el-cascader :options="treeList" clearable @change="changetree" :props="defaultProps" />
      </div>
      <div style="width: 100%;text-align: center;margin-top: 10px">
        <el-button type="primary" @click="updatesubmit">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog v-model="updatedeviceshow" title="转入设备" width="500">
      <div>

        <el-select v-model="devicevalue" placeholder="Select" size="large" multiple style="width: 240px"
          @change="changesel">
          <el-option v-for="item in devicelist" :key="item.id" :label="item.device_name" :value="item.id" />
        </el-select>
      </div>
      <div style="width: 100%;text-align: center;margin-top: 10px">
        <el-button type="primary" @click="devicesubmit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "statisticalAnalysis",
  inheritAttrs: false,
});
import { initMap } from "@/common/map";
import ElectronicFence from "./component/electronicFence.vue";
import Historical from "./component/Historical.vue";

import account from "./component/account.vue";
import warining from "./component/warning.vue";
import CustomerAPI from "@/api/customer";
import DeviceManagementApi, { ManagementPage, ManagementPageList } from "@/api/deviceManagement"
import UserAPI, { UserPageQuery } from "@/api/user";
import DeviceApi, { distributeDevice } from "@/api/device"
import RoleAPI from "@/api/role";
import { usePermissionStore } from "@/store";
const permissionStore = usePermissionStore();
const currentRoute = useRoute();
// 查找包含 "name": "accountManagement" 的对象
const accountManagementRoute = permissionStore.routes
  .flatMap(route => route.children) // 将所有 children 展开
  .find(child => child ? child.name === currentRoute.name : false)?.children;
function resolvePath(routePath: string) {

  // 完整绝对路径 = 父级路径(/system) + 路由路径(/user)
  // const fullPath = path.resolve(props.basePath, routePath);
  return routePath;
}
/**
@date: 2024-08-29 11:14:51
右键菜单的样式
*/
let rightTreeMenuStyle = {};
/**
@date: 2024-08-29 11:15:19
右键控制菜单是否隐藏
*/
let treeRightMenuShow = ref(false);
const DeptTrees = ref<any>()
const defaultProps = {

  checkStrictly: true,
  value: "id",
  label: "customerName",
  children: "children"
}

// 重置密码
function resetPsw() {
  console.log(formData, queryParams.value.customerId);

  let data = {
    customerId: formData.customer.parentId
  }
  let customerId = formData.customer.parentId
  UserAPI.resetPassword(customerId).then(() => {

  })
}
function refresh() {
  DeptTrees.value.getCustomerTree()
}


const formData = reactive<RuleForm>({
  customer: {
    parentId: '',
    enableFlag: 'ENABLE'

  },
  contact: {
    enableFlag: 'ENABLE'
  }
})
const deviceRules = reactive({
  'customer.customerName': [
    { required: true, message: '不能为空', trigger: 'blur' },
  ],
  'contact.name': [
    { required: true, message: '不能为空', trigger: 'blur' },
  ],
  'contact.username': [
    { required: true, message: '不能为空', trigger: 'blur' },
  ],
  'contact.password': [
    { required: true, message: '不能为空', trigger: 'blur' },
  ],
  // 'contact.customerId': [
  //   { required: true, message: '不能为空', trigger: 'change' },
  // ],
  'contact.roleIdList': [
    { required: true, message: '不能为空', trigger: 'change' },
  ],
  'contact.phone': [
    { required: true, message: '不能为空', trigger: 'blur' },
  ],


})
/**
 * 打开弹窗
 *
 * @param id 用户ID
 */
/**  用户弹窗对象  */
const dialog = reactive({
  visible: false,
  title: "",
});
const loading = ref(false);
/** 部门下拉选项 */
const deptOptions = ref<OptionType[]>();
/** 角色下拉选项 */
const roleOptions = ref<OptionType[]>();

async function handleOpenDialog(code?: string) {
  dialog.visible = true;
  // 加载角色下拉数据源
  roleOptions.value = await RoleAPI.getOptions();
  // // 加载部门下拉数据源
  // deptOptions.value = []
  // deptOptions.value.push(await CustomerAPI.getCustomerTree())

  if (code) {
    dialog.title = "编辑客户";
    CustomerAPI.getselectCustomerAndContact(formData.customer.parentId).then((data) => {
      // const { createTime, ...rest } = data;
      Object.assign(formData, data);
      console.log(777, data);
    });
  } else {
    // console.log('xinzeng',code);
    dialog.title = "新增客户";
  }
}

/** 表单提交 */
const userFormRef = ref(ElForm);

const handleSubmit = useThrottleFn(() => {
  userFormRef.value.validate((valid: any) => {
    if (valid) {

      loading.value = true;
      if (dialog.title === '编辑客户') {
        CustomerAPI.upCustomer(formData)
          .then(() => {
            ElMessage.success("修改用户成功");
            dialog.visible = false;
          })
          .finally(() => (loading.value = false));
      } else {
        CustomerAPI.addCustomer(formData)
          .then(() => {
            ElMessage.success("新增用户成功");
            dialog.visible = false;
            refresh()

          })
          .finally(() => (loading.value = false));
      }
    }
  });
}, 3000);
// 转入设备
// 转移客户弹出层
let filters = reactive<ManagementPage>({
  "pages": {
    "current": 1,
    "size": 10,
    "total": 0,
    "startTime": "",
    "endTime": "",
    "orders": [
      {
        "column": "",
        "asc": true
      }
    ]
  },
  // deviceStatus:'',
  // onlineStatus:'',
  // expireStatus:'',
  deviceTypeId: '',
  customerId: '',
  isChild: true
});
let updatedeviceshow = ref(false);
interface devicetype {
  id: string;
  device_name: string;
}
let devicelist = ref<devicetype[]>([])
let devicevalue = ref('')
function updatedevice() {
  updatedeviceshow.value = true
  devicevalue.value = ''
  devicelist.value = []

  DeviceManagementApi.getManagementPage(filters)
    .then((data) => {

      devicelist = data.data.records
      console.log(data, '000', devicelist);

    })
}

// 转移客户弹出层
let treeList = ref<OptionType[]>([])
let pid = ref('')
function changetree(value: any) {
  console.log(value.length, '===', value);
  pid.value = value[value.length - 1]

}
let updateshow = ref(false);

function updatecustomer() {
  updateshow.value = true
  treeList.value = []
  CustomerAPI.getCustomerTree().then((res) => {
    treeList.value.push(res)

  })

}
// 转入设备选择
let seldevice = ref([])
function changesel(data: any) {
  console.log(data);
  seldevice.value = data
}

function devicesubmit() {
  // console.log(data,devicevalue);
  // devicevalue.value
  let data = {
    customerId: `${formData.customer.parentId}`,
    deviceId: seldevice.value
  }


  DeviceApi.BatchAllocate(data).then((res) => {
    ElMessage({
      message: '配对成功',
      type: 'success',
    })
    updatedeviceshow.value = false

  })

}
interface RuleForm {
  customer: customer;
  contact: contact;
}
interface customer {
  id?: string,
  customerName?: string,
  parentId: string,
  contactId?: string,
  enableFlag?: string
}
interface contact {
  /** 用户头像 */
  avatar?: string;
  /** 部门ID */
  deptId?: number;
  /** 邮箱 */
  email?: string;
  /** 性别 */
  gender?: number;
  /** 用户ID */
  id?: number;
  /** 手机号 */
  mobile?: string;
  /** 昵称 */
  nickname?: string;
  /** 角色ID集合 */
  roleIds?: number[];
  /** 用户状态(1:正常;0:禁用) */
  status?: number;
  /** 用户名 */
  username?: string;
  /** 用户名称 */
  name?: string;
  /** 用户密码 */
  password?: string;
  /** 所属客户 */
  customerId?: string;
  /** 角色 */
  roleIdList?: string[];
  /** 手机号 */
  phone?: string;
  /** 状态 */
  enableFlag?: string;
  /** 创建时间 */
  createTime?: string;
}

//转移客户提交按钮 
function updatesubmit() {
  let data = {

    parentId: pid.value,
    id: formData.customer.parentId
  }
  CustomerAPI.updatecustomer(data).then((res) => {
    refresh()
    ElMessage({
      message: '转移客户成功',
      type: 'success',
    })
    updateshow.value = false
  })
}
// 删除客户
function deletecustomer() {
  // let data={
  let id = formData.customer.parentId
  // }
  // console.log(formData,queryParams.customerId);

  CustomerAPI.deletecustomer(id).then(() => {

  })
}
/**
 鼠标右键 
 */
let fatherID = ref()
function contextmenuClick(event: any, data: any, node: any) {
  treeRightMenuShow.value = true;
  formData.customer.parentId = data//本身id
  fatherID.value = node.parentId//父id
  // console.log(fatherID.value,data);

  console.log(event, '===============');

  //防止右键菜单底部被覆盖 --可以自己根据右键菜单的高度调整
  let jianPx = 0;
  if (document.documentElement.clientHeight - event.pageY < 200) {
    jianPx = 200;
  }
  //右键菜单的位置
  rightTreeMenuStyle = {
    top: event.pageY - jianPx + "px",
    left: event.pageX + "px",
  };
  //点击页面其他地方关闭右键菜单
  document.addEventListener("click", (ev) => {
    hideRightMenu();
  });
}
function hideRightMenu() {
  treeRightMenuShow.value = false;
  //关闭点击页面其他地方关闭右键菜单的监听
  document.removeEventListener("click", hideRightMenu);
}




// 监视 customerId 的变化
//  watch(() => queryParams.customerId, (newId) => {
//       console.log('Customer ID changed to:', newId);
//       // 更新 uniqueKey 以触发子组件重渲染
//       componentToShow.value=componentToShow.value
//     });
const AllchildRef = ref<any>(null);
/** 查询 */
function handleQuery(node: any) {
  console.log(queryParams.value.customerId, '----------------', node);
  if (node) {
    queryParams.value.customerId = node.id
  }

  // setTimeout(() => {
  //   AllchildRef.value.getManagementPage();
  // }, 50)
}


let componentToShow: any = ref(Historical);
let deptId = ref(0);
const total = ref(0);
/** 用户查询参数  */
const queryParams = ref({
  pageNum: 1,
  pageSize: 100,
  customerId: '1'
});


const deptList: any = [
  {
    value: 1,
    label: "有来技术",
    children: [
      {
        value: 2,
        label: "研发部门",
      },
      {
        value: 3,
        label: "测试部门",
      },
    ],
  },
];

function handleSelect(key: any) {
  componentToShow.value = judgePath(key)
}

const judgePath = (path: any) => {
  if (path === 'ElectronicFence') {
    return ElectronicFence
  } else if (path === 'account') {
    return account
  } else if (path === 'warining') {
    return warining
  }
  else if (path === 'Historical') {
    return Historical

  }
}

onMounted(() => {
});

</script>
<style lang="scss" scoped>
.tree_rightmenu {
  z-index: 1000;
  position: fixed;
  padding: 5px 0;
  margin: 0;
  background-color: #fff;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  box-shadow: 2px 2px 8px 0 hsla(0, 0%, 59%, 0.2);
  list-style: none;
  font-size: 14px;
  white-space: nowrap;
  cursor: pointer;

  .tree_rightmenu_item {
    padding: 2px 14px;
    color: #333;

    &:hover {
      background-color: #46a0fc;
      color: #fff;
    }
  }
}

.locationIndexPage {
  display: flex;
  // flex-wrap: wrap;
  // flex-direction: column;
  height: calc(100vh - 120px);
  box-sizing: border-box;
  padding: 10px 10px 10px 5px;
  overflow: hidden;

  .menu-container {
    width: 320px;
    height: 100%;
    position: relative;
    display: flex;
    flex-direction: column;
    justify-content: space-between;

    .custom-wrapper {
      width: 100%;
      margin: 0px;
      background: #2b2b2b;
      border-radius: 3px;
      position: relative;
      height: 232px;

      .titles {
        padding: 0px;
        height: 24px;
        line-height: 24px;
        text-align: center;
        font-size: 15px;
        border-bottom: 1px solid #4d4d4d;
        color: #fff;
      }

      :deep(.el-card__body) {
        padding-top: 0;

      }

      :deep(.el-tree-node__content:hover) {
        background-color: #40a0ff4e !important;

      }

      :deep(.el-tree-node.is-current>.el-tree-node__content) {
        background-color: #409eff !important;

      }

      :deep(.el-tree-node:focus>.el-tree-node__content) {
        background-color: #409eff !important;

      }
    }

    .device-wrapper {
      margin: 0px 5px 0px 0px;
      width: 100%;
      height: calc(100% - 232px - 10px);
      // margin-top: 10px;
      padding: 5px;
      box-sizing: border-box;
      overflow: hidden;
      background: #2b2b2b;
      border-radius: 3px;

      :deep(.el-menu) {
        border-right: 0;
      }
    }
  }

  .map-container {
    width: calc(100% - 10px - 320px);
    margin-left: 10px;
    position: relative;
    background: #2b2b2b;
    border-radius: 3px;
    height: 100%;
    padding-left: 10px;
  }
}

// 复用样式
.warp {
  color: #fff;
  background: #1c1c1c;
  border-radius: 5px;
}
</style>
<style lang="scss">
.sortingLocation {
  .el-dropdown-menu.el-dropdown-menu--default {
    background-color: #fff !important;

  }
}


.el-popper__arrow:before {
  background: #fff !important;
  border: 1px solid #fff !important;
}

// /* 定制滚动条整体 */
::-webkit-scrollbar {
  width: 8px;
  height: 8px;
  background-color: #9d9d9d;
}

/* 定制滚动条轨道 */
::-webkit-scrollbar-track {
  background-color: #f1f1f1;
  /* 轨道颜色 */
}

/* 定制滚动条滑块 */
::-webkit-scrollbar-thumb {
  background-color: #9d9d9d;
  /* 滑块颜色 */
  border-radius: 6px;
  /* 圆角 */
}

/* 滑块在鼠标悬停时改变颜色 */
::-webkit-scrollbar-thumb:hover {
  background-color: #747373;
}
</style>
